import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/customer/register',
    name: 'CustomerRegister',
    component: () => import('../views/customer/Register.vue')
  },
  {
    path: '/employee/register',
    name: 'EmployeeRegister',
    component: () => import('../views/employee/Register.vue')
  },
  {
    path: '/customer/home',
    name: 'CustomerHome',
    component: () => import('../views/customer/Home.vue')
  },
  {
    path: '/employee/home',
    name: 'EmployeeHome',
    component: () => import('../views/employee/Home.vue')
  },
  {
    path: '/manager',
    redirect: '/manager/login'
  },
  {
    path: '/manager/login',
    name: 'ManagerLogin',
    component: () => import('../views/manager/Login.vue')
  },
  {
    path: '/manager/home',
    name: 'ManagerHome',
    component: () => import('../views/manager/Home.vue'),
    redirect: '/manager/rooms',
    children: [
      {
        path: '/manager/employees',
        name: 'Employees',
        component: () => import('../views/manager/Employees.vue') 
      },
      {
        path: '/manager/customers',
        name: 'Customers',
        component: () => import('../views/manager/Customers.vue')
      },
      {
        path: '/manager/rooms',
        name: 'Rooms',
        component: () => import('../views/manager/Rooms.vue')
      },
      {
        path: '/manager/devices',
        name: 'Devices',
        component: () => import('../views/manager/Devices.vue') 
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 登录和注册页面不需要验证token
  if (to.path.includes('/login') || to.path.includes('/register')) {
    next()
    return
  }

  // 根据不同端检查token并重定向
  if (to.path.includes('/manager')) {
    if (!token && localStorage.getItem('username')!=='admin') {
      next('/manager/login')
      return
    }
  } 
  else if (!token) {
    next('/login')
    return
  }
  next()
})

export default router